package com.cunyme;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import java.io.IOException;
import java.util.Vector;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

//public class Forum extends Activity
public class Forum extends ListActivity
{
	int i = 0;
	int length = 0;
	int sIteratorBegin = 0;
	int sIteratorEnd = 0;
	String pageSource;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forum);       
        // Set up post button and login listener
		Button myPostButton = (Button)findViewById(R.id.post_button);
	    myPostButton.setOnClickListener(myPostButtonListener);
	    
	    Vector<String> myPosts = new Vector<String>(); 
	    
        try { 
        	Document page = Jsoup.connect("http://s88157295.onlinehome.us/forum/comments.php").get();
        	pageSource = page.text(); 
        	sIteratorBegin = pageSource.indexOf("~1");
        	
        	while (sIteratorBegin != -1 && i < 64)
        	{      
        		sIteratorBegin = sIteratorBegin + 2;
        		sIteratorEnd = pageSource.indexOf("1~", sIteratorBegin);
        		myPosts.add("Title: " +pageSource.substring(sIteratorBegin, sIteratorEnd) + "\nPost: "
        		+ pageSource.substring(pageSource.indexOf("~2", sIteratorBegin) + 2, pageSource.indexOf("2~", sIteratorBegin)) + "\nName: "
        		+ pageSource.substring(pageSource.indexOf("~3", sIteratorBegin) + 2, pageSource.indexOf("3~", sIteratorBegin)) + "\nDate: "
        		+ pageSource.substring(pageSource.indexOf("~4", sIteratorBegin) + 2, pageSource.indexOf("4~", sIteratorBegin)));
        		sIteratorBegin = sIteratorEnd;
        		sIteratorBegin = pageSource.indexOf("~1", sIteratorBegin);
        		i++;  
        	}
        } catch (IOException e) {  
        	e.printStackTrace();
        }
        
        String[] postS = new String[myPosts.size()];
        for(int i=0; i<myPosts.size(); i++){
        	postS[i]=myPosts.elementAt(i);
        }
        
        
        
        ArrayAdapter<String> forumAdapter;
        forumAdapter = new ArrayAdapter<String>(
        	this,
        	R.layout.forum_item,
        	postS);        
        setListAdapter(forumAdapter);   
        getListView().setTextFilterEnabled(true);
    }
    OnClickListener myPostButtonListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
	        // Going to post view
			Intent gotoForumPost = new Intent(Forum.this, ForumPost.class);
			startActivity(gotoForumPost);	
			finish();
		}
	};
}
